// 全局配置和工具函数
const config = {
    apiBaseUrl: 'http://api.example.com',
    refreshInterval: 5000, // 数据刷新间隔（毫秒）
};

// 工具函数
const utils = {
    // 格式化日期
    formatDate(date) {
        return new Date(date).toLocaleString('zh-CN');
    },
    
    // 发送API请求
    async fetchData(endpoint) {
        try {
            const response = await fetch(`${config.apiBaseUrl}${endpoint}`);
            return await response.json();
        } catch (error) {
            console.error('数据获取失败:', error);
            return null;
        }
    }
};

// 在原有代码基础上添加
class PageManager {
    static init() {
        this.setupNavigation();
        this.handleActiveLink();
        this.setupPageTransitions();
    }

    static setupNavigation() {
        document.querySelectorAll('.nav-links a').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault(); // 阻止默认跳转
                const href = link.getAttribute('href');
                this.navigateToPage(href);
            });
        });
    }

    static handleActiveLink() {
        const currentPage = window.location.pathname.split('/').pop() || 'index.html';
        this.updateActiveLink(currentPage);
    }

    static updateActiveLink(href) {
        document.querySelectorAll('.nav-links a').forEach(link => {
            if (link.getAttribute('href') === href) {
                link.classList.add('active');
            } else {
                link.classList.remove('active');
            }
        });
    }

    static async navigateToPage(href) {
        const mainContainer = document.querySelector('.main-container');
        
        try {
            // 添加退出动画
            mainContainer.classList.add('page-exit');
            
            // 获取新页面内容
            const response = await fetch(href);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const html = await response.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const newContent = doc.querySelector('.main-container');

            if (!newContent) {
                throw new Error('New content not found in fetched page');
            }

            // 等待退出动画完成
            await new Promise(resolve => setTimeout(resolve, 200));

            // 更新 URL
            window.history.pushState({}, '', href);
            
            // 清理旧页面资源
            this.cleanupCurrentPage();

            // 更新内容
            mainContainer.innerHTML = newContent.innerHTML;
            mainContainer.className = newContent.className;
            
            // 移除退出动画类
            mainContainer.classList.remove('page-exit');
            
            // 初始化新页面
            this.initNewPage(href);
            
            // 更新导航状态
            this.updateActiveLink(href);

        } catch (error) {
            console.error('页面加载失败:', error);
            // 发生错误时直接跳转
            window.location.href = href;
        }
    }

    static cleanupCurrentPage() {
        // 清理视频流
        const videos = document.querySelectorAll('video');
        videos.forEach(video => {
            if (video.srcObject) {
                const tracks = video.srcObject.getTracks();
                tracks.forEach(track => track.stop());
                video.srcObject = null;
            }
            video.pause();
        });

        // 清理图表实例
        if (window.echarts) {
            const charts = document.querySelectorAll('.chart');
            charts.forEach(chart => {
                const instance = echarts.getInstanceByDom(chart);
                if (instance) {
                    instance.dispose();
                }
            });
        }
    }

    static initNewPage(href) {
        // 根据页面类型初始化相应功能
        if (href.includes('video.html')) {
            new VideoMonitoring();
        } else if (href.includes('growth.html')) {
            new GrowthMonitoring();
        } else if (href.includes('disaster.html')) {
            new DisasterMonitoring();
        } else if (href.includes('remote-sensing.html')) {
            new RemoteSensingAnalysis();
        }

        // 触发页面初始化事件
        const event = new CustomEvent('pageInitialized', { detail: { page: href } });
        document.dispatchEvent(event);
    }

    static setupPageTransitions() {
        // 处理浏览器的前进后退
        window.addEventListener('popstate', () => {
            const currentPage = window.location.pathname.split('/').pop() || 'index.html';
            this.navigateToPage(currentPage);
        });
    }
}

// 初始化页面管理器
document.addEventListener('DOMContentLoaded', () => {
    PageManager.init();
}); 